<?php

/*
 * LoginForm class
 * LoginForm is the data structure for keeing user login form data
 * It is used by the 'login' action 
 */

class AdminLoginForm extends CFormModel {

    public $username;
    public $password;
    public $rememberme;
    private $_identity;

    public function rules() {
        return array(
            array('username,password', 'required'),
            array('rememberme', 'boolean'),
            array('password', 'validateLogin'),
        );
    }

    /*
     * Declares attribute labels
     */
    public function attributeLabels() {
        return array(
            'rememberme' => 'Nhớ đăng nhập lần sau',
            'username' => 'Tên đăng nhập',
            'password' => 'Mật khẩu',
        );
    }

    /*
     * Authenticates the password
     */

    public function validateLogin() {

        if (!$this->hasErrors()) {
            $this->_identity = new AdminIdentity($this->username, $this->password);
            if ($this->_identity->authenticate()) {

                switch ($this->_identity->errorCode) {
                    //if user is denied
                    case AdminIdentity::ERROR_STATE_INVALID:

                        $this->addError('username', 'User is wrong');
                        break;
                    case AdminIdentity::ERROR_PASSWORD_INVALID:

                        $this->addError('password', 'Password is wrong');
                        break;
                }
            }
        }
    }

    public function login() {

        if ($this->_identity === null) {
            $this->_identity = new AdminIdentity($this->username, $this->password);
            $this->_identity->authenticate();
        }

        if ($this->_identity->errorCode === AdminIdentity::ERROR_NONE) {

            $duration = $this->rememberme ? 3600 * 24 * AdminSession::REMEMBER_DAYS : 0; // 30 days
            Yii::app()->admin->login($this->_identity, $duration);
            
            $model = User::model()->loadByAccount($this->username);
            
            Yii::app()->admin->setState('admin_id', $model->getAttribute('admin_id'));
            Yii::app()->admin->setState('area', Yii::app()->params['area']['admincp']);
            //TODO set other variables.
            $model->setAttribute('update_time', date('Y-m-d H:i:s'));
            $model->save();

            return true;
        } else {
            
            return false;
        }
    }
}

